<template>
  <div class="add-customer">
    <el-card>
      <template #header>
        <h3>新增客户</h3>
      </template>

      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          label-position="top"
      >
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户姓名" />
        </el-form-item>

        <el-form-item
            label="手机号码"
            prop="phone"
            :validate-status="phoneStatus"
            :error="phoneError"
        >
          <el-input
              v-model="form.phone"
              placeholder="请输入手机号码"
              @blur="checkPhoneUnique"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            提交
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { customerApi } from '@/api'
import { ElMessage } from 'element-plus'

const router = useRouter()
const formRef = ref(null)
const submitting = ref(false)
const phoneStatus = ref('')
const phoneError = ref('')

const form = ref({
  name: '',
  phone: ''
})

const rules = {
  name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 检查手机号是否唯一
const checkPhoneUnique = async () => {
  if (!form.value.phone || !/^1[3-9]\d{9}$/.test(form.value.phone)) return

  try {
    const response = await customerApi.checkPhone(form.value.phone)
    if (response.state === 1000) {
      phoneStatus.value = 'error'
      phoneError.value = response.message
    } else {
      phoneStatus.value = 'success'
      phoneError.value = ''
    }
  } catch (error) {
    console.error('检查手机号失败:', error)
  }
}

const submitForm = async () => {
  try {
    // 先验证表单
    await formRef.value.validate()

    submitting.value = true
    const response = await customerApi.addCustomer(form.value)

    // 根据状态码处理响应
    if (response.state === 1000) {
      // 手机号已注册情况
      phoneStatus.value = 'error'
      phoneError.value = response.message
      ElMessage.error(response.message)
    } else if (response.state === 2000) {
      // 成功情况
      ElMessage.success('客户添加成功')
      router.push('/customers')
    } else {
      // 其他错误
      ElMessage.error(response.message || '添加客户失败')
    }
  } catch (error) {
    // 网络错误或验证失败
    if (error.response?.data?.state === 1000) {
      phoneStatus.value = 'error'
      phoneError.value = error.response.data.message
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error(error.message || '添加客户失败')
    }
    console.error('添加客户错误:', error)
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  formRef.value.resetFields()
  phoneStatus.value = ''
  phoneError.value = ''
}
</script>

<style scoped>
.add-customer {
  max-width: 600px;
  margin: 0 auto;
}
</style>